package com.block.source.service.receive;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.KaiXinHuaParam;
import com.block.source.model.api.YiRongGuangGaoParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceReceiveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class KaiXinHuaReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();
        String channelCode = sourceBaseInfo.getChannelCode();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息为空"));
            return sourceApiResult;
        }
        String data = jsonObjectParamContent.getString("data");

        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(data);
        JSONObject jsonObject = JSONObject.parseObject(paramContentData);
        //过滤
        if (StrUtil.isEmpty(jsonObject.getString("phone_mask")) || StrUtil.isEmpty(jsonObject.getString("name")) || jsonObject.getInteger("age") == null ||
                jsonObject.getInteger("sex") == null || StrUtil.isEmpty(jsonObject.getString("province") ) || StrUtil.isEmpty(jsonObject.getString("city") ) ||
                jsonObject.getInteger("occupation") == null || jsonObject.getInteger("education") == null || jsonObject.getInteger("social_security") == null ||
                jsonObject.getInteger("accumulation_fund") == null || jsonObject.getInteger("house") == null || jsonObject.getInteger("car") == null ||
                jsonObject.getInteger("insurance") == null || jsonObject.getInteger("sesame") == null || jsonObject.getInteger("education") == null
        || jsonObject.getInteger("weilidai") == null || jsonObject.getInteger("overdue")  == null ||  jsonObject.getInteger("credit_card") == null  ||  jsonObject.getInteger("loan_amount") == null
        || jsonObject.getInteger("loan_time") == null || jsonObject.getInteger("month_income") == null ||  jsonObject.getInteger("business_license") == null
        || StrUtil.isEmpty(jsonObject.getString("request_id")) ||  StrUtil.isEmpty(jsonObject.getString("client_ip"))) {
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息有空值"));
            return sourceApiResult;
        }

        UserDataParam userDataParam = this.getUserDataParam(paramContentData);


        // 通过城市编码,获取城市信息
        String city = jsonObject.getString("city");

        AddressInfo addressInfo = addressInfoService.getAddresInfoByCity(city);
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getError("城市信息为空"));
            return sourceApiResult;
        }

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());



        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecret = sourceBaseInfo.getApiSecret();

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("进件传入的信息为空"));
            return sourceApiResult;
        }
        String content = jsonObjectParamContent.getString("data");
        String paramContentData = SecureUtil.aes(apiSecret.getBytes()).decryptStr(content);

        KaiXinHuaParam KaiXinHuaParam = JSON.parseObject(paramContentData, KaiXinHuaParam.class);

        UserDataParam userDataParam = this.getUserDataParam(paramContentData);

        userDataParam.setMobile(KaiXinHuaParam.getPhone());
        userDataParam.setRealName(KaiXinHuaParam.getName());

        String productId = KaiXinHuaParam.getProduct_id();
        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(sourceBaseInfo.getChannelCode(), productId);
        userDataParam.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {


        SourceApiResult sourceApiResult = new SourceApiResult();

        MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();
        MerchantThirdBaseInfo thirdBaseInfo = sourceApiParam.getThirdBaseInfo();
        List<MerchantThirdProtocolInfo> thirdProtocolInfoList = sourceApiParam.getThirdProtocolInfoList();

        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 200);
        returnObject.put("msg", "撞库成功");
        JSONArray dataObject1 = new JSONArray();
        JSONObject dataObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        if (StrUtil.equals(merchantBaseInfo.getInfoType(), InfoTypeEnum.APIS.getValue())){
            dataObject.put("companyName", thirdBaseInfo.getCompanyName());
            String companyLogo = thirdBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", companyLogo);
            }
            dataObject.put("productName", thirdBaseInfo.getProductName());
            dataObject.put("productId", pushResultInfo.getOutOrderNo());
            dataObject.put("price", Float.valueOf(String.valueOf(pushResultInfo.getPriceAmount())));

            //协议地址
            for (MerchantThirdProtocolInfo protocolInfo : thirdProtocolInfoList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("protocolName",protocolInfo.getProtocolName());
                jsonObject.put("protocolUrl", protocolInfo.getProtocolUrl());
                jsonArray.add(jsonObject);
            }
        }else {
            dataObject.put("companyName", merchantBaseInfo.getCompanyName());
            String companyLogo = merchantBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", merchantBaseInfo.getCompanyLogo());
            }
            dataObject.put("productName", merchantBaseInfo.getInfoName());
            dataObject.put("productId", pushResultInfo.getOutOrderNo());
            dataObject.put("price", Float.valueOf(String.valueOf(pushResultInfo.getPriceAmount())));
            //协议地址

            JSONObject jsonObject = new JSONObject();
            ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(sourceBaseInfo.getChannelCode());
            ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(baseInfoByCode.getAppCode());
            String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), pushResultInfo.getOrderNo(), pushResultInfo.getOrderItemNo());
            jsonObject.put("protocolName","授权协议");
            jsonObject.put("protocolUrl", protocolUrl);
            jsonArray.add(jsonObject);
        }

        JSONObject data = resultInfoVO.getData();
        JSONArray md5List = data.getJSONArray("md5List");
        dataObject.put("phone_md5_lists", md5List != null ? md5List : new JSONArray());

        dataObject.put("protocolList", jsonArray);
        dataObject1.add(dataObject);
        returnObject.put("data", dataObject1);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO,SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        JSONObject returnObject = new JSONObject();

        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();
        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                returnObject = this.getSuccess();
                sourceApiResult.setReturnObject(returnObject);
                return sourceApiResult;
            }
        }

        returnObject = this.getError("进件失败");
        JSONObject jsonObject = new JSONObject();
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 500);
        returnObject.put("msg", message);
        returnObject.put("data", new JSONArray());
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("code", 200);
        returnObject.put("msg", "进件成功");
        return returnObject;
    }

    @Override
    public UserDataParam getUserDataParam(String paramContent) {

        KaiXinHuaParam kaiXinHuaParam = JSON.parseObject(paramContent, KaiXinHuaParam.class);

        UserDataParam userDataParam = new UserDataParam();

        Integer randomInt = RandomUtil.randomInt(Integer.MAX_VALUE);
        userDataParam.setOutOrderNo(String.valueOf(randomInt));

        userDataParam.setMobileMask(kaiXinHuaParam.getPhone_mask());
        userDataParam.setMobile(kaiXinHuaParam.getPhone());
        userDataParam.setRealName(kaiXinHuaParam.getName());

        Integer sex = kaiXinHuaParam.getSex();
        if (sex == 0){
            userDataParam.setSex("1");
        }else {
            userDataParam.setSex("2");
        }


        userDataParam.setAge(Integer.valueOf(kaiXinHuaParam.getAge()));
        AddressInfo addresInfoByCity = addressInfoService.getAddresInfoByCity(kaiXinHuaParam.getCity());
        userDataParam.setCityCode(addresInfoByCity.getCityCode());


        Integer creditCardLimit = kaiXinHuaParam.getCredit_card();
        if (creditCardLimit == 1){
            userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        }else {
            userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk002.getValue());
        }

        userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt001.getValue());

        Integer education = kaiXinHuaParam.getEducation();
        if (education == 1){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl001.getValue());
        }else if (education == 2 || education == 3 ||  education == 4){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl002.getValue());
        }else if (education == 5){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl003.getValue());
        }else if (education == 6){
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl004.getValue());
        }else {
            userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl005.getValue());
        }

        Integer monthIncome = kaiXinHuaParam.getMonth_income();
        if(monthIncome == 1){
            userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr002.getValue());
        }else if(monthIncome == 2){
            userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr003.getValue());
        }else if(monthIncome == 3 || monthIncome == 4){
            userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr004.getValue());
        }


        userDataParam.setWeili(BaseTypeInfoEnum.WeiLi.wl001.getValue());

        Integer baitiao = kaiXinHuaParam.getBaitiao();
        if (baitiao == 1){
            userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt001.getValue());
        }
        userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt002.getValue());


        Integer huabei = kaiXinHuaParam.getHuabei();
        if (huabei == 1){
            userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());
        }
        userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb002.getValue());


        String ip = kaiXinHuaParam.getClient_ip();
        if (StringUtils.isNotEmpty(ip)){
            userDataParam.setUserIp(ip);
        }else {
            userDataParam.setUserIp("127.0.0.1");
        }


        Integer loanAmount = kaiXinHuaParam.getLoan_amount();
        if (loanAmount == 1) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
        } else if (loanAmount ==2) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la002.getValue());
        } else if (loanAmount ==3) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la003.getValue());
        } else if (loanAmount ==4) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la004.getValue());
        } else {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la005.getValue());
        }


        Integer houseProperty = kaiXinHuaParam.getHouse();
        if (houseProperty == 1){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
        }else {
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu002.getValue());
        }


        Integer baodanIs = kaiXinHuaParam.getInsurance();
        if (baodanIs == 1){
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx001.getValue());
        }else {
            userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx002.getValue());
        }


        Integer overdue = kaiXinHuaParam.getOverdue();
        if (overdue == 1 || overdue == 4){
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());
        }else if(overdue == 2){
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq002.getValue());
        }else if(overdue == 3){
            userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq003.getValue());
        }


        Integer gongjijin = kaiXinHuaParam.getAccumulation_fund();
        if (gongjijin == 1){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
        }else if (gongjijin == 2 || gongjijin == 3){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj002.getValue());
        }

        Integer sesame = kaiXinHuaParam.getSesame();
        if (sesame == 1){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm001.getValue());
        }else if (sesame == 2){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm002.getValue());
        }else if (sesame == 3){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm003.getValue());
        }else if (sesame == 4){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm004.getValue());
        }else {
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm005.getValue());
        }

        Integer shebao = kaiXinHuaParam.getSocial_security();
        if (shebao == 1){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
        }
        userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb002.getValue());


        Integer car = kaiXinHuaParam.getCar();
        if (car == 1){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
        }
            userDataParam.setCar(BaseTypeInfoEnum.Car.car002.getValue());


        Integer job = kaiXinHuaParam.getOccupation();
        if (job == 5){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz004.getValue());
        }else if (job == 2){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz002.getValue());
        }else if (job == 3){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz003.getValue());
        }else if(job == 4){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz005.getValue());
        }
        userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());

        userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt001.getValue());


        return userDataParam;
    }


}
